package exemplo.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class DataBaseConnection {
	
	private Connection connection;

	public DataBaseConnection() throws SQLException, ClassNotFoundException {
		if (connection == null) {
			connect();
		}
	}
	
	private void connect() throws SQLException, ClassNotFoundException {
		Class.forName("com.mysql.jdbc.Driver");
		connection = DriverManager.getConnection("jdbc:mysql://localhost/jsfexample", "root", "");
	}
	public Connection getConnection() throws SQLException, ClassNotFoundException {
		if (connection == null) {
			connect();
		}
		return connection;
	}
	
	public Statement getStatement() throws SQLException, ClassNotFoundException {
		return getConnection().createStatement();
	}
	
	public PreparedStatement getPreparedStatement(String sql) throws SQLException, ClassNotFoundException {
		return getConnection().prepareStatement(sql);
	}
	
	public void close() throws SQLException {
		if (connection != null) {
			connection.close();
		}
	}
}
